package com.frontop.terminal.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.gangedsocket.config.PlayGangedConfig;
import com.frontop.terminal.gangedsocket.core.PlayGangedClient;
import com.frontop.terminal.gangedsocket.core.PlayGangedServiceSocket;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.WriteDataUtil;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p>
 * 服务器配置控制器
 * </P>
 *
 * @author :CCC
 * @since :2021-05-19 09:33:00
 **/
@Controller
@RequestMapping("/terminal-config")
@RequiredArgsConstructor
public class TerminalConfigController {


    @GetMapping("")
    public String config(HttpServletRequest request) {
        TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();
        if (Objects.isNull(terminalConfig)) {
            terminalConfig = new TerminalConfig();
        }
        terminalConfig.setLocalSocketAddress(PlayGangedConfig.HOST_ADDRESS);
        request.setAttribute("terminalConfig", terminalConfig);
        return "config";
    }

    @PostMapping("")
    @ResponseBody
    public RestResult save(@RequestBody TerminalConfig terminalConfig) {
        try {
            //子目录不存在则创建
            String resourcePath = terminalConfig.getResourceAddress();
            boolean fileExistStatus = FileUtil.exist(resourcePath);
            if (!fileExistStatus) {
                FileUtil.mkdir(resourcePath);
            }

            //窗口大小与窗口位置参数校验
            RestResult paramIllegal = checkdata(terminalConfig);
            if (paramIllegal != null) {
                return paramIllegal;
            }

            //播放联动
            playGanged(terminalConfig);

            String json = JSON.toJSONString(terminalConfig);
            System.out.println(json);
            WriteDataUtil.write(terminalConfig, ReadDataUtil.TERMINAL_CONFIG_CODING);

            //通知服务器同步 TODO 待优化开启

//            TerminalConfigBo terminalConfigBo = BeanUtil.toBean(terminalConfig, TerminalConfigBo.class);
//            terminalConfigBo.setHide(terminalConfig.isPlayerHide());
//            terminalConfigBo.setFullScreen(terminalConfig.isBrowserFullScreen());
//
//            String url = terminalConfig.getServerAddress() + ConstInterface.UPDATE_TERMINAL_CONFIG;
//            String mac = SystemMonitoringUtil.getMacAddress();
//            terminalConfigBo.setMac(mac);
//            String result = HttpRequest.put(url)
//                    //设置连接超时和响应超时时间
//                    .timeout(3000)
//                    .header(HeaderEnum.TERMINAL_TOKEN.getKey(), terminalConfig.getAuthorizationCode())
//                    .contentType(ContentType.JSON.getValue())
//                    .body(JSON.toJSONString(terminalConfigBo))
//                    .execute().body();
//
//            //打印结果
//            System.out.println("同步终端配置-服务器响应:" + result);
//            if ("true".equals(result)) {
//                return RestResult.success();
//            }

            return RestResult.success();
        } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
            return RestResult.failed("服务器地址格式错误，建议提交前先测试地址是否能与服务器连接成功");
        } catch (IORuntimeException e) {
            //忽略服务器同步时离线引起的异常
            e.printStackTrace();
            return RestResult.success();
        }
    }

    /**
     * 播放联动
     *
     * @param terminalConfig 配置
     */
    private void playGanged(TerminalConfig terminalConfig) {
        TerminalConfig localConfig = ReadDataUtil.getTerminalConfig();
        if (Objects.nonNull(localConfig)) {
            boolean playerGangen = terminalConfig.isPlayerGanged();
            //比对播放联动配置有更改
            if (playerGangen != localConfig.isPlayerGanged()) {
                //开启
                if (playerGangen) {
                    //服务端或客户端启动或者关闭
                    serverOrClientStartOrClose(terminalConfig, localConfig);

                } else {
                    //关闭播放联动
                    //释放服务端服务
                    PlayGangedServiceSocket.release();
                    //释放服务端服务
                    PlayGangedClient.release();

                    //所有标志设置关闭状态
                    terminalConfig.setPlayerGangedClient(false);
                    terminalConfig.setPlayerGangedServer(false);
                }

            } else if (playerGangen) {
                //服务端或客户端启动或者关闭
                serverOrClientStartOrClose(terminalConfig, localConfig);
            } else {
                //关闭播放联动
                //释放服务端服务
                PlayGangedServiceSocket.release();
                //释放服务端服务
                PlayGangedClient.release();
            }

        }
    }

    /**
     * 服务端或客户端启动或者关闭
     *
     * @param terminalConfig 配置
     * @param localConfig    本地配置
     */
    private void serverOrClientStartOrClose(TerminalConfig terminalConfig, TerminalConfig localConfig) {
        //对比选项[本机作为服务端]是否有更改
        if (terminalConfig.isPlayerGangedServer() != localConfig.isPlayerGangedServer()) {
            //启动本机播放联动socket服务端
            if (terminalConfig.isPlayerGangedServer()) {
                PlayGangedServiceSocket.start();
            } else {
                //释放服务端服务
                PlayGangedServiceSocket.release();
            }
        } else if (terminalConfig.isPlayerGangedServer() == localConfig.isPlayerGangedServer()) {
            localConfig.setPlayerGangedServer(localConfig.isPlayerGangedServer());
        } else if (terminalConfig.isPlayerGangedServer()) {
            //启动本机播放联动socket服务端
            PlayGangedServiceSocket.start();
        } else {
            //释放服务端服务
            PlayGangedServiceSocket.release();
        }

        //对比选项[本机作为客户端]是否有更改
        if (terminalConfig.isPlayerGangedClient() != localConfig.isPlayerGangedClient()) {
            //本机作为客户端
            if (terminalConfig.isPlayerGangedClient()) {
                PlayGangedClient.start();
            } else {
                //释放服务端服务
                PlayGangedClient.release();
            }
        } else if (terminalConfig.isPlayerGangedClient() == localConfig.isPlayerGangedClient()) {
            localConfig.setPlayerGangedClient(terminalConfig.isPlayerGangedClient());
        } else if (terminalConfig.isPlayerGangedClient()) {
            //本机作为客户端
            PlayGangedClient.start();
        } else {
            //释放服务端服务
            PlayGangedClient.release();
        }
    }

    /**
     * 窗口大小与窗口位置参数校验
     *
     * @param terminalConfig 终端配置
     * @return http状态码对象
     */
    @Nullable
    private RestResult checkdata(TerminalConfig terminalConfig) {
        //取出播放器窗口数据校验
        String playerSize = terminalConfig.getPlayerSize();
        //取出播放器位置数据校验
        String playerLocation = terminalConfig.getPlayerLocation();
        String symbol = "-";
        int range = 2;
        //校验播放器窗口数据
        if (null != playerSize && !"".equals(playerSize)) {
            //数据中不包含 “-”
            if (!playerSize.contains(symbol)) {
                return RestResult.failed("播放器窗口参数必须以'-'分隔");
            }
            //截取宽度和高度
            String[] windthOrHieght = playerSize.split(symbol);
            //正确数据大小只有2
            if (windthOrHieght.length != range) {
                return RestResult.failed("播放器窗口参数填写有误");
            }
        }

        //校验播放器窗口数据
        if (null != playerLocation && !"".equals(playerLocation)) {
            //数据中不包含 “-”
            if (!playerLocation.contains(symbol)) {
                return RestResult.failed("播放器位置参数必须以'-'分隔");
            }
            //截取宽度和高度
            String[] xOrY = playerLocation.split(symbol);
            //正确数据大小只有2
            if (xOrY.length != range) {
                return RestResult.failed("播放器位置参数填写有误");
            }
        }
        return null;
    }

    /**
     * 测试与服务器的通讯是否连通
     *
     * @param terminalConfig 配置对象
     * @return RestResult
     */
    @PostMapping("test")
    @ResponseBody
    public String test(@RequestBody TerminalConfig terminalConfig) {
        //获取服务器配置地址拼装完整接口
        String url = terminalConfig.getServerAddress() + InterfaceConst.TEST;
        String result;
        Boolean status;
        try {
            result = HttpRequest.get(url)
                    //设置连接超时和响应超时时间
                    .timeout(3000)
                    .header(HeaderEnum.TERMINAL_TOKEN.getKey(), terminalConfig.getAuthorizationCode())
                    .execute()
                    .body();
            status = JSON.parseObject(result, Boolean.class);
        } catch (Exception e) {
            return "连接超时";
        }

        if (status) {
            return "连接成功";
        } else {
            return "连接超时";
        }
    }
}
